<!doctype>
<html>
<head>
<title>Service</title>
</head>
<body>
<?php

if(!isset($_POST['submit'])){
	echo "<form action='?page=service' method='post'>
		<p>
			Select format <select name='service' id='service'>
				<option value='json'>JSON Document</option>
				<option value='xml'>XML Document</option>
			</select>
		</p>
		<input type='submit' name='submit' value='Select'>
	</form>";
	}

else{
	$db = new DBconnect();
	$service_info = array();
	$query = $db->selectAllRealPlayers();
	while($player = mysql_fetch_assoc($query)){
		$name = $player['player_name'];
		$value = $player['value'];
		$player_team = $player['team_name'];
		$imageURL = "http://localhost/FManagerPHP/images/realplayers/".$name.".jpg";
		$real_player = array("player_name"=>$name,"team_name"=>$player_team,"value"=>$value, "image"=>$imageURL);
		array_push($service_info, $real_player);
	}
	
	if($_POST['service'] == 'json'){
		$json = json_encode($service_info, JSON_PRETTY_PRINT);
		$file = fopen("service/JSON-Service.json", "w");
		fwrite($file, $json);
		fclose($file);
		header("Location:service/JSON-Service.json");
	}	
		
	if($_POST['service'] == 'xml'){
		$xml = new DOMDocument();
		$xml_players = $xml->createElement("allplayers");
		$xml->appendChild($xml_players);
		$count = count($service_info);
		for($i = 0; $i < $count; $i++){
			$xml_player = $xml->createElement("player");
			$xml_players->appendChild($xml_player);
			$name = $xml->createElement("player_name", $service_info[$i]['player_name']);
			$team = $xml->createElement("team_name", $service_info[$i]['team_name']);
			$value = $xml->createElement("value", $service_info[$i]['value']);
			$imageURL = $xml->createElement("image", "http://localhost/FManagerPHP/images/realplayers/".$service_info[$i]['player_name'].".jpg");
			$xml_player->appendChild($name);
			$xml_player->appendChild($team);
			$xml_player->appendChild($value);
			$xml_player->appendChild($imageURL);
		}
		$xml->formatOutput = true;
		$xml->save("service/XML-Service.xml");
		header("Location:service/XML-Service.xml");
	}
}
?>
</body>
</html>